﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using e_commerce.BLL.Data;

namespace e_commerce.BLL.Services.Enterprise
{
    public class EmployeeService:IDisposable
    {
        private commerceDbContext _dbContext;
        private AccountService _aService;
        public EmployeeService()
        {
            _aService = new AccountService();
            _dbContext = new commerceDbContext();
        }

        public IEnumerable<Employee> GetAllEmployees()
        {
            return _dbContext.Employee;
        }

        public IEnumerable<Employee> GetEmployeeByPage(int page,int size,ref int total)
        {
            var employees = (from e in _dbContext.Employee
                             orderby e.Id
                             select e).Skip((page - 1) * size).Take(size);
            total = _dbContext.Employee.Count();
            return employees;
        }
        public int CreateEmployee(User user)
        {
            user.Password = user.Password == null ? "123456" : user.Password;
            var newUser = _aService.CreateUser(user);
            Employee employee = new Employee()
            {
                UserId = newUser.UserId,
            };
            _dbContext.Employee.Add(employee);
            SaveChange();
            return employee.Id;
        }

        public Employee GetEmployee(int employeeId)
        {
            var employee = _dbContext.Employee.SingleOrDefault(e => e.Id == employeeId);
            if(employee == null)
            {
                throw new Exception("employee not found");
            }
            return employee;
        }

        public void DeleteEmployee(int employeeId)
        {
            var employee = GetEmployee(employeeId);
            var user = _aService.GetUserById(employee.Id);
            user.Permissions.Clear();
            user.Role.Clear();
            _dbContext.Employee.Remove(employee);
            _dbContext.User.Remove(user);
            SaveChange();
        }
        public void SaveChange()
        {
            _dbContext.SaveChanges();
        }

        public void Dispose()
        {
            _dbContext.Dispose();
        }
    }
}
